﻿// JavaScript Document

function openDialog(dialog){
    document.getElementById(dialog).style.display = "block";
    document.getElementById(dialog).style.visibility = "visible";
}

function closeDialog(dialog){
    document.getElementById(dialog).style.visibility = "hidden";
    document.getElementById(dialog).style.display = "none";
}

function submitVerifycode(e){
	var keynum = 0;
	if(window.event){
		keynum = e.keyCode;
	}else if(e.which){
		keynum = e.which;
	}
	if(keynum == 13){
		document.getElementById("validateButton").focus(); 
		document.getElementById("validateButton").click(); 
	}
}

function selectTab(tab){
	for(var i=1;i<4;i++){
		document.getElementById("setting_tab_" + i).className = "setting_dialog_tab";
	}
	document.getElementById(tab).className = "setting_dialog_tab_select";
	
	closeDialog('setting_base_area');
	closeDialog('setting_farm_area');
	closeDialog('setting_feed_area');
	if(tab == "setting_tab_1"){
		openDialog('setting_base_area');
	}else if(tab == "setting_tab_2"){
		openDialog('setting_farm_area');
	}else if(tab == "setting_tab_3"){
		openDialog('setting_feed_area');
	}
}

function print(debugText){
   debug.innerHTML += debugText;
};

function println(debugText){
   debug.innerHTML += debugText + "<br/>";
};

window.happyfarm = {};
happyfarm.util = {};

var defClass = function(objNS, strName, objSuper, fctDef){
    var noInit = {};
    
    var c = objNS[strName] = function(){
        if (arguments[0] !== noInit) 
            this.init.apply(this, arguments);
    };
    
    if (objSuper) {
        c.prototype = new objSuper(noInit);
        
        c._super = function(fct, arrArgs){
            if (!arrArgs) 
                arrArgs = [];
            var sf = objSuper.prototype[fct];
            
            return sf.apply(this, arrArgs);
        };
    }
    
    fctDef(c, c.prototype);
};
	
function doValidate(){
}

function saveLoginConfig(){
	if(document.getElementById("u").value !="" && document.getElementById("p").value !="" && document.getElementById("verifycode").value !=""){
		//保存登录配置
		var tools = new happyfarm.util.Tools();
		var content = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "\n";
		content += "<login>" + "\n";
		content += "<user userId=\"" + document.getElementById("u").value + "\" userPwd=\"" + document.getElementById("p").value + "\"/>" + "\n";
		content += "</login>";
		tools.saveConfig(content, "login", "root", false);
	}
}

//取得登录配置
function getLoginConfig(){
	var tools = new happyfarm.util.Tools();
    var fct = function(xmlDoc){
        var rs = xmlDoc.getElementsByTagName("user");
		if(rs.length > 0){
			document.getElementById("u").value = rs[0].getAttribute("userId");
			document.getElementById("p").value = rs[0].getAttribute("userPwd");
		}
    };
    tools.getConfig("login.config", fct);
}

function $(obj){
	return document.getElementById(obj);
}


function initialization(){
	document.getElementById("login_msg").innerHTML = "&nbsp;";
	document.getElementById("login_error").innerHTML = "&nbsp;";
	
    var appLoader = new happyfarm.util.AppLoader();
    var job = new happyfarm.util.Job();
	var request = new happyfarm.util.Request();
	var tools = new happyfarm.util.Tools();
	
	//debug
	debug = document.getElementById("debug");
	
	// firefox,打开跨域访问权限
    if (navigator.userAgent.indexOf("Firefox") > 0) {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
    }
	if(host == ""){
		if (document.getElementById("host1").checked) {
			host = document.getElementById("host1").value;
		} else {
			host = document.getElementById("host2").value;
		}
	}
    
    
    if (timer) {
        window.clearInterval(timer);
    }
	
	//用户登录。
	document.getElementById("login_msg").innerHTML = "正在登录";
	Concurrent.Thread.sleep(20);
	var url = "http://ptlogin2.qq.com/check?uin="+document.getElementById("loginUserId").value+"&appid=15000101&r="+Math.random();
	var result = request.doGetCommon(url, null);
	
	var verifycode = result.substr(18, 4);
	
	url = "http://ptlogin2.qq.com/login?";
	url += "u=" + document.getElementById("loginUserId").value;
	url += "&p=" + md5_3(document.getElementById("loginUserPwd").value, verifycode);
	url += "&verifycode=" + verifycode;
	url += "&aid=15000101";
	url += "&u1=http%3A%2F%2Fimgcache.qq.com%2Fqzone%2Fv5%2Floginsucc.html%3Fpara%3Dizone";
	url += "&ptredirect=1";
	url += "&h=1";
	url += "&from_ui=1";
	url += "&dumy=";
	url += "&fp=loginerroralert";
	
	result = request.doGetCommon(url, null);
	
	if(result.indexOf("密码有误") > 0){
		document.getElementById("login_msg").innerHTML = "&nbsp;";
		document.getElementById("login_error").innerHTML = "登录帐号或密码错误，请重新登录";
		return;
	}
	
	document.getElementById("login_msg").innerHTML = "初始化全部农作物的信息";
	Concurrent.Thread.sleep(20);
    //初始化全部农作物的信息
    cropsInfo = job.getSeedInfo();
    if (cropsInfo == null) {
        alert("商店信息取得失败，请重新登录！");
        return;
    } else if (cropsInfo.errorType) {
		alert("农场连接失败，可能是由于没有登录！");
        return;
    }
	
	document.getElementById("login_msg").innerHTML = "生成我的信息";
    //显示我的信息
    document.getElementById("person_area").style.display = "block";
	Concurrent.Thread.sleep(20);
    //生成登录人的信息
    var result = job.getUserInfo();
    var levelArray = tools.getLevel(result.exp);
	if(result.user.headPic == ""){
    	document.getElementById("myPic").src = "http://qlogo.store.qq.com/qzone/" + result.user.uinLogin + "/" + result.user.uinLogin + "/100";
	}else{
		document.getElementById("myPic").src = result.user.headPic;
	}
    document.getElementById("myName").innerHTML = "自己";
    document.getElementById("myExp").innerHTML = result.exp;
    document.getElementById("myMoney").innerHTML = result.user.money;
    document.getElementById("myLevel").innerHTML = levelArray[0];
    document.getElementById("myLastExp").innerHTML = levelArray[1];
        
	//取得用户农场信息,并生成列表
	appLoader.getFarmConfig(result.farmlandStatus);
	farmArray = result.farmlandStatus;
	
	document.getElementById("login_msg").innerHTML = "取得仓库信息";
	Concurrent.Thread.sleep(20);
    //取得仓库信息
    getUserCrop();
	
	document.getElementById("login_msg").innerHTML = "取得远程所有好友列表";
    //显示好友区域
    document.getElementById("friend_area").style.display = "block";
	Concurrent.Thread.sleep(20);
	
    //取得远程所有好友列表
    userArray = job.getUserList(result);
    if (userArray == null) {
        alert("好友列表获取失败，请重新登录！");
        return;
    } else if (userArray.errorType) {
		alert("农场连接失败，可能是由于没有登录！");
    	return;
    }
        
	//取得偷菜配置文件，并生成列表
	appLoader.getCropsConfig();
    //取得系统配置文件
    appLoader.getSysConfig();
    //取得本地好友配置文件，并生成列表
    appLoader.getfriendConfig();
	
	document.getElementById("login_msg").innerHTML = "取得用户背包信息";
	Concurrent.Thread.sleep(20);
    //取得用户背包信息
	getUserSeed();
        
    //显示控制按钮
    document.getElementById("ctrl_area").style.display = "block";
	
	//关闭登陆界面
	document.getElementById("login_dialog").style.display = "none";
    
    //版本检测
    window.setTimeout(function(){
        var appLoader = new happyfarm.util.AppLoader();
        appLoader.checkUpgrade();
    }, 1000);
}

//取得用户背包信息
function getUserSeed(){
	var job = new happyfarm.util.Job();
	try {
		var result = job.getUserSeed();
		readyCrops = new Array();
		for (var i = 0; i < result.length; i++) {
			//生成种子列表
			if (result[i].type == 1) {
				for (var j = 0; j < result[i].amount; j++) {
					appLoader.addReadyCrops(result[i].cId, result[i].cName, 1);
				}
			}
			//生成普通化肥
			if (result[i].type == 3 && result[i].tId == 1) {
				fertilizerNum = result[i].amount;
			}
		}
	} catch (e) {
    
    }
}

//取得用户仓库信息
function getUserCrop(){
    var job = new happyfarm.util.Job();
    //取得用户仓库信息
    try {
        var userCrop = job.getUserCrop();
        if (userCrop) {
            var sumCrop = 0;
            var sumPrice = 0;
            for (var i = 0; i < userCrop.length; i++) {
                sumCrop += parseInt(userCrop[i].amount);
                sumPrice += parseInt(userCrop[i].amount) * parseInt(userCrop[i].price);
            }
            document.getElementById("sumCrop").innerHTML = sumCrop;
            document.getElementById("sumPrice").innerHTML = sumPrice;
        }
    } catch (e) {
    
    }
}

//变卖全部果实
function saleAllCrops(){
    var job = new happyfarm.util.Job();
    //取得用户仓库信息
    try {
        var crops = job.getUserCrop();
		crops = crops.crop;
		var cropStr = "";
		for(var i=0;i<crops.length;i++){
			if(i == crops.length - 1){
				cropStr += crops[i].cId;
			}else{
				cropStr += crops[i].cId + ",";
			}
		}
        job.saleAllCrops(crops);
        getUserCrop();
        //生成登录人的信息
        var result = job.getUserInfo();
        
        if (result) {
            if (result.user) {
                var levelArray = tools.getLevel(result.exp);
                document.getElementById("myExp").innerHTML = result.exp;
                document.getElementById("myMoney").innerHTML = result.user.money;
                document.getElementById("myLevel").innerHTML = levelArray[0];
                document.getElementById("myLastExp").innerHTML = levelArray[1];
            }
        }
    } catch (e) {
    
    }
}

//刷经验
function startExp(){
    
    //初期化expInfo
    var userExpList = document.getElementById("userExpList");
    while (userExpList.childNodes.length > 0) {
        userExpList.removeChild(userExpList.childNodes[0]);
    }
    
    //创建一个线程
    Concurrent.Thread.create(mainExp);
}

function mainExp(){
    var job = new happyfarm.util.Job();
    var tools = new happyfarm.util.Tools();
    var request = new happyfarm.util.Request();
    
    //如果启动刷经验功能
    var num = document.getElementById("num").value;
    
    var blbNum = 0;
    var seeds = job.getUserSeed();
    for (var i = 0; i < seeds.length; i++) {
        //生成种子列表
        if (seeds[i].type == 1) {
            //判断背包中有多少牧草
            if (seeds[i].cId == "40") {
                blbNum = seeds[i].amount;
            }
        }
    }
    
    if (num - blbNum> 0) {
        //购买指定数量牧草
        job.buySeeds("40", num - blbNum);
    }
    
    var hoeingSum = 0;
    var farmingSum = 0;
    
	var brushExpInterval = parseInt(document.getElementById("brushExpInterval").value);
    //在第一块农田上刷经验
    for (var i = 0; i < num; i++) {
		var hoeingCount = 0;
		var farmingCount = 0;
		
        landRow = document.createElement("tr");
        landRow.setAttribute("id", "landRow" + i);
        landRow.setAttribute("align", "center");
        //隔行换色
        if (i % 2 != 0) {
            landRow.className = "row-bgcolor";
        }
        
        landCell = document.createElement("td");
		landCell.setAttribute("width", "50px");
        landCell.appendChild(document.createTextNode("第" + (i + 1) + "次"));
        landRow.appendChild(landCell);
        
        //锄地
        var hoeingExp = job.hoeing(myId, 0);
		if(hoeingExp){
			if(hoeingExp.exp){
				hoeingCount = hoeingExp.exp;
				hoeingSum += hoeingExp.exp;
			}
		}
        
        landCell = document.createElement("td");
		landCell.setAttribute("width", "50px");
        landCell.appendChild(document.createTextNode(hoeingCount));
        landRow.appendChild(landCell);
        
        //种地
        var farmingExp = job.farming("40", myId, 0);
		if(farmingExp){
			if(farmingExp.exp){
				farmingCount = farmingExp.exp;
				farmingSum += farmingExp.exp;
			}
		}
        
        landCell = document.createElement("td");
		landCell.setAttribute("width", "50px");
        landCell.appendChild(document.createTextNode(farmingCount));
        landRow.appendChild(landCell);
        
        landCell = document.createElement("td");
		landCell.setAttribute("width", "50px");
        landCell.appendChild(document.createTextNode("完成"));
        landRow.appendChild(landCell);
        
        //生成一个人的农场信息
        document.getElementById("userExpList").appendChild(landRow);
        
        //生成的收获信息合计
        document.getElementById("hoeingSum").innerHTML = hoeingSum;
        document.getElementById("farmingSum").innerHTML = farmingSum;
        
        //更新数量
        document.getElementById("num").value = document.getElementById("num").value - 1;
        
        document.getElementById("userExpList").scrollTop =  document.getElementById("userExpList").scrollHeight;
        
        //线程中断brushExpInterval秒
        Concurrent.Thread.sleep(brushExpInterval);
    }
    
    //生成登录人的信息
    var result = job.getUserInfo();
    
    if (result) {
        if (result.user) {
            var levelArray = tools.getLevel(result.exp);
            document.getElementById("myExp").innerHTML = result.exp;
            document.getElementById("myMoney").innerHTML = result.user.money;
            document.getElementById("myLevel").innerHTML = levelArray[0];
            document.getElementById("myLastExp").innerHTML = levelArray[1];
        }
    }
    
    closeDialog("expDialog");
    
    window.setTimeout(function(){
        var warehouse = job.getUserSeed();
        
        //初始化
        readyCrops = new Array();
        for (var i = 0; i < warehouse.length; i++) {
            //生成种子列表
            if (warehouse[i].type == 1) {
                for (var j = 0; j < warehouse[i].amount; j++) {
                    appLoader.addReadyCrops(warehouse[i].cId, warehouse[i].cName, 1);
                }
            }
        }
    }, 0);
}

function startApp(){
    //初期化自动维护倒计时器
	for(var i=0;i<10;i++){
    	window.clearInterval(interval[i]);
	}
    window.clearTimeout(timeout);
	
    //目标农田信息集合初始化
    targetMission = [];
	
    //初期化immediateList
    //document.getElementById("immediateList").innerHTML = "";
	
    //初期化dialog
    document.getElementById("progMain").innerHTML = "0%";
    document.getElementById("progMain").style.width = "";
    
	//相关设定读取
	window.borers_run = document.getElementById("borers").checked;
	window.weeds_run = document.getElementById("weeds").checked;
	window.dryland_run = document.getElementById("dryland").checked;
	window.auto_crops_run = document.getElementById("Auto-crops").checked;
	window.auto_farm_run = document.getElementById("Auto-farm").checked;
	window.dog_run = document.getElementById("dog").checked;
	window.crope_run = document.getElementById("crope").checked;
	window.dogCrops1_id = document.getElementById("dogCrops1").value;
	window.dogCrops2_id = document.getElementById("dogCrops2").value;
	window.dogCrops3_id = document.getElementById("dogCrops3").value;
	window.intervalTimeValue = document.getElementById("intervalTimeValue").value;
	window.intervalTimeCheck = document.getElementById("intervalTimeCheck").checked;
	
	
    document.getElementById("startApp").disabled="disabled";
	
    //显示dialog
    openDialog("proDialog");
	
    //显示log
    openDialog("log_area");
    
	var appLoader = new happyfarm.util.AppLoader();
	//遍历所有田地上的农作物信息
	for(var i=0;i<userArray.length;i++){
    	farmlandStatus(i);
		creatDetails(i);
		//更新进度条
        appLoader.updateProgressBars(i+1, userArray.length);
		Concurrent.Thread.sleep(1);
	}
	runMission();
	
    //显示dialog
    closeDialog("proDialog");
}

function farmlandStatus(userIndexId){
	var tools = new happyfarm.util.Tools();
	var job = new happyfarm.util.Job();
	var request = new happyfarm.util.Request();
	
	if (userArray[userIndexId].check) {
		var url = "";
		if (userArray[userIndexId].uin) {
			host = "http://nc.qzone.qq.com/cgi-bin/"
		} else {
			host = "http://nc.xiaoyou.qq.com/cgi-bin/"
        }
        var sendTime = tools.getLocalTime();
		var uId = null;
		var uin = null;
		var flag = null;
		if(myId == userArray[userIndexId].uId){
			flag = "1";
		}else{
			uId = userArray[userIndexId].uId;
			uin = userArray[userIndexId].uin;
		}
		
		var postData = "ownerId=" + userArray[userIndexId].uId;
        var result = request.doPostRequest(postData, "cgi_farm_index?", "user", "run", flag, userArray[userIndexId].uin);
        //获取本地时间
		var localTime = sendTime;
		result = eval('(' + result.responseText + ')');
        
        //获取服务器时间
        var serverTime = 0;
        if (result.user) {
			serverTime = result.user.healthMode.serverTime;
        }
        //初始化一个好友的农场
        userArray[userIndexId]["indexId"] = userIndexId;
        userArray[userIndexId]["farmlandStatus"] = [];
        
        if (!result.farmlandStatus) {
            return;
        }
        //显示农场是否有狗
        if (result.dog) {
            //判断狗是否是饥饿状态(当狗还有1小时饥饿时就喂狗)
            if (result.dog.isHungry) {
                //添加有狗粮属性
                userArray[userIndexId]["dog"] = true;
                //判断是否是自己的狗
                if (myId == userArray[userIndexId].uId) {
                    if (document.getElementById("Auto-feed").checked) {
                        //喂狗
                        this.feedDog();
                    }
                }
            }
        } else {
            userArray[userIndexId]["dog"] = false;
        }
        
        //初始化统计变量
        userArray[userIndexId]["expCount"] = 0;
        userArray[userIndexId]["glodCount"] = 0;
        //开始遍历农场信息
        for (var i = 0; i < result.farmlandStatus.length; i++) {
            //初始化一个好友的一个农田
            userArray[userIndexId]["farmlandStatus"][i] = [];
            //初始化统计变量
            userArray[userIndexId]["farmlandStatus"][i]["weedsCount"] = 0;
            userArray[userIndexId]["farmlandStatus"][i]["borersCount"] = 0;
            userArray[userIndexId]["farmlandStatus"][i]["dryLand"] = false;
            userArray[userIndexId]["farmlandStatus"][i]["cropCount"] = 0;
            //初始化状态变量
            userArray[userIndexId]["farmlandStatus"][i]["landStatus"] = "";
            userArray[userIndexId]["farmlandStatus"][i]["cropStatus"] = -1;
            userArray[userIndexId]["farmlandStatus"][i]["time"] = 0;
            
            //获得农作物的ID
            var cId = result.farmlandStatus[i].a;
            
            //获取农作物的信息
            var crops = job.getCropsInfo(cId);
            
            //首先判断地里是否有农作物
            if (crops != null) {
                //农作物是否长杂草
                var weedsNum = result.farmlandStatus[i].f;
                //农作物是否生虫子
                var borersNum = result.farmlandStatus[i].g;
                //农作物是否干旱
                var dryland = result.farmlandStatus[i].h;
                //农作物成熟时间=农作物种植时间 + 成长时间 - 现在服务器时间
                var time = parseInt(result.farmlandStatus[i].q) + parseInt(crops.growthCycle) - parseInt(serverTime);
                
                //健康模式开启
                if (result.user.healthMode.set == 1) {
                    var matureTime = parseInt(result.farmlandStatus[i].q) + parseInt(crops.growthCycle);
                    matureTime = new Date(matureTime * 1000);
                    matureTime = matureTime.getHours();
                    //剔除健康模式期间成熟的作物
                    if (matureTime >= 0 && matureTime < 6) {
                        continue;
                    }
                }
                //添加作物名称
                userArray[userIndexId]["farmlandStatus"][i]["landStatus"] = crops.cName;
                
                //是否有虫
                if (borersNum > 0) {
                    if (window.borers_run) {
                        //清除虫子
                        for (var n = 0; n < borersNum; n++) {
                            job.clearBorers(userArray[userIndexId].uId, i, userIndexId, userArray[userIndexId].uin);
                        }
                    }
                }
                
                //是否有草
                if (weedsNum > 0) {
                    if (window.weeds_run) {
                        //清除杂草
                        for (var n = 0; n < weedsNum; n++) {
                            job.clearWeeds(userArray[userIndexId].uId, i, userIndexId, userArray[userIndexId].uin);
                        }
                    }
                }
                
                //是否干旱
                if (dryland == 0) {
                    if (window.dryland_run) {
                        //灌溉旱地
                        job.irrigation(userArray[userIndexId].uId, i, userIndexId, userArray[userIndexId].uin);
                    }
                }
                
                //收获果实
                //判断果实是否成熟
                if (result.farmlandStatus[i].q == 0) {
                    //判断是否是自己的地
                    if (myId == userArray[userIndexId].uId) {
                        //是否启用自动种菜功能
                        if (window.auto_crops_run) {
                            //锄地
                            job.hoeing(userArray[userIndexId].uId, i, userIndexId, userArray[userIndexId].uin);
                            //耕种
                            job.doFarming(userArray[userIndexId], i, userIndexId, userArray[userIndexId].uin);
                        }
                    } else {
                        //该地里面的果实已经收光了
                        userArray[userIndexId]["farmlandStatus"][i]["landStatus"] = "荒地";
                    }
                } else if (time <= 3600) {
                    //判断是否是自己的地，是否启用防偷盗系统
                    if (myId == userArray[userIndexId].uId && document.getElementById("Anti-theft").checked) {
                        if (time > 0) {
                            //如果自己本身没有化肥
                            if (fertilizerNum == 0) {
                                //购买化肥
                                job.buyFertilizer();
                            }
                            //施肥
                            job.fertilization(userArray[userIndexId].uId, i);
                            time = time - 3600;
                        }
                    }
                    //判断是否成熟
                    if (time <= 0) {
                        //判断是否是自己的地
                        if (myId == userArray[userIndexId].uId) {
                            //收获果实
                            job.getCrops(userArray[userIndexId].uId, i, 1, userIndexId, userArray[userIndexId].uin);
                            userArray[userIndexId]["farmlandStatus"][i]["cropStatus"] = 0;
                            //是否启用自动种菜功能
                            if (window.auto_crops_run) {
                                for (var c = 0; c < cropsInfo.length; c++) {
                                    //从种子列表中找到当前的种子信息
                                    if (cId == cropsInfo[c].cId) {
                                        //当前农作物所处的种植季判断，以便来区分是否可以锄地
                                        if (result.farmlandStatus[i].j == parseInt(cropsInfo[c].maturingTime) - 1) {
                                            //锄地
                                            job.hoeing(userArray[userIndexId].uId, i, userIndexId, userArray[userIndexId].uin);
                                            //耕种
                                            job.doFarming(userArray[userIndexId], i, userIndexId, userArray[userIndexId].uin);
                                        }
                                        break;
                                    }
                                }
                            }
                        } else {
                            //判断是否偷过
                            var stole = true;
                            var rogueList = result.farmlandStatus[i].n;
                            for (var farmlandOwner in rogueList) {
                                if (farmlandOwner == myId) {
                                    userArray[userIndexId]["farmlandStatus"][i]["cropStatus"] = 4;
                                    stole = false;
                                    break;
                                }
                            }
                            if (stole) {
                                //判断可以偷
                                if (result.farmlandStatus[i].l < result.farmlandStatus[i].m) {
                                    //有狗也可以偷
                                    if (window.dog_run || !result.dog || result.dog.isHungry) {
                                        if (window.crope_run) {
                                            //开始偷盗他人果实
                                            job.getCrops(userArray[userIndexId].uId, i, 0, userIndexId, userArray[userIndexId].uin);
                                            userArray[userIndexId]["farmlandStatus"][i]["cropStatus"] = 0;
                                        } else {
                                            userArray[userIndexId]["farmlandStatus"][i]["cropStatus"] = 1;
                                        }
                                    } else {
                                        userArray[userIndexId]["farmlandStatus"][i]["cropStatus"] = 2;
                                    }
                                } else {
                                    userArray[userIndexId]["farmlandStatus"][i]["cropStatus"] = 3;
                                }
                            }
                        }
                    }
                } else if (time > 3600) {
                    //各个阶段自动施肥
                    var n = i;
                    if (myId == userArray[userIndexId].uId && document.getElementById("Auto-fertilizer").checked) {
                        tools.getConfig("ini.xml", function(xmlDoc){
                            var crop = xmlDoc.getElementsByTagName("crop");
                            for (var i = 0; i < crop.length; i++) {
                                if (cId == crop[i].getAttribute("id")) {
                                    var cTime = crop[i].getAttribute("value");
                                    cTime = cTime.split(",");
                                    if (time > parseInt(cTime[cTime.length - 1]) - parseInt(cTime[cTime.length - 2])) {
                                        var job = new happyfarm.util.Job();
                                        //如果自己本身没有化肥
                                        if (fertilizerNum == 0) {
                                            //购买化肥
                                            job.buyFertilizer();
                                        }
                                        //施肥
                                        job.fertilization(userArray[userIndexId].uId, n);
                                        break;
                                    }
                                }
                            }
                        });
                    }
                }
                //如果没有选择有狗也偷，而此农场有狗，则不把农场的农作物的成熟时间做最短时间进行判断
                if (window.crope_run || myId == userArray[userIndexId].uId) {
                    if (window.dog_run || !result.dog || result.dog.isHungry || myId == userArray[userIndexId].uId) {
                        var theft = false;
                        if (window.dog_run && result.dog && !result.dog.isHungry && myId != userArray[userIndexId].uId) {
                            if (cId != window.dogCrops1_id && cId != window.dogCrops2_id && cId != window.dogCrops3_id) {
                                theft = true;
                            }
                        } else {
                            theft = true;
                        }
                        if (time > 0) {
                            if (theft) {
                                //是否选择了偷取该作物
                                for (var j = 0; j < cropsInfo.length; j++) {
                                    if (cropsInfo[j].cId == cId && cropsInfo[j].check) {
                                        var target = {};
                                        target["time"] = time;
                                        target["owner"] = userArray[userIndexId];
                                        target["farm"] = result.farmlandStatus[i];
                                        target["farm"]["cName"] = crops.cName;
                                        //取得该作物的种植季
                                        target["farm"]["harvestTimes"] = cropsInfo[j].maturingTime;
                                        target["farmIndex"] = i;
                                        target["localTime"] = localTime;
                                        target["serverTime"] = serverTime;
                                        if (result.dog && !result.dog.isHungry) {
                                            target["dogIsHungry"] = true
                                        } else {
                                            target["dogIsHungry"] = false;
                                        }
										target["run"] = true;
                                        targetMission.push(target);
                                        break;
                                    }
                                }
                            }
                            //生成倒计时
                            userArray[userIndexId]["farmlandStatus"][i]["time"] = tools.culTime(time);
                        }
                    } else {
                        userArray[userIndexId]["farmlandStatus"][i]["time"] = tools.culTime(time);
                    }
                }
            } else {
                //判断是否是自己的地
                if (myId == userArray[userIndexId].uId) {
                    //是否启用自动种菜功能
                    if (window.auto_crops_run) {
                        //耕种
                        job.doFarming(userArray[userIndexId], i, userIndexId, userArray[userIndexId].uin);
                    }
                } else {
                    //该地里面的是空地
                    userArray[userIndexId]["farmlandStatus"][i]["landStatus"] = "空地";
                }
            }
        }
    }
}

//生成每块土地的详细信息
function creatDetails(i){
	if(userArray[i].farmlandStatus){
		//生成必要的统计信息
		for(var j=0;j<userArray[i].farmlandStatus.length;j++){
		
			if(userArray[i].farmlandStatus[j].weedsCount>0){
				addLog(userArray[i].userName, "第"+(j+1)+"块地", "除草", userArray[i].farmlandStatus[j].weedsCount, true, "");
			}
			
			if(userArray[i].farmlandStatus[j].borersCount>0){
				addLog(userArray[i].userName, "第"+(j+1)+"块地", "杀虫", userArray[i].farmlandStatus[j].borersCount, true, "");
			}
			
			if(userArray[i].farmlandStatus[j].dryLand){
				addLog(userArray[i].userName, "第"+(j+1)+"块地", "灌溉", 1, true, "");
			}
			
			if(userArray[i].farmlandStatus[j].cropStatus == 0){
				if(userArray[i].farmlandStatus[j].cropCount > 0){
					if(userArray[i].uId == myId){
						addLog(userArray[i].userName, "第"+(j+1)+"块地", "果实", userArray[i].farmlandStatus[j].cropCount, true, "丰收");
					}else{
						addLog(userArray[i].userName, "第"+(j+1)+"块地", "果实", userArray[i].farmlandStatus[j].cropCount, true, "");
					}
				}else{
					addLog(userArray[i].userName, "第"+(j+1)+"块地", "果实", 0, false, userArray[i].farmlandStatus[j].direction);
				}
			}
		}
	}
}

function addLog(userName, no, name, num, status, msg){
	var tbody = document.getElementById("log_msg");
	
	var tr = document.createElement("tr");
	var td = document.createElement("td");
	td.setAttribute("width", "200px");
	td.className = "log_msg";
	td.appendChild(document.createTextNode(new Date().toLocaleString())); 
	tr.appendChild(td);	
	var td = document.createElement("td");
	td.setAttribute("width", "150px");
	td.className = "log_msg";
	td.appendChild(document.createTextNode(userName)); 
	tr.appendChild(td);
	var td = document.createElement("td");
	td.setAttribute("width", "150px");
	td.className = "log_msg";
	td.appendChild(document.createTextNode(no)); 
	tr.appendChild(td);
	var td = document.createElement("td");
	td.setAttribute("width", "150px");
	td.className = "log_msg";
	td.appendChild(document.createTextNode(name)); 
	tr.appendChild(td);
	var td = document.createElement("td");
	td.setAttribute("width", "250px");
	td.className = "log_msg";
	td.appendChild(document.createTextNode(num)); 
	tr.appendChild(td);
	var td = document.createElement("td");
	td.setAttribute("width", "50px");
	td.className = "log_msg";
	if(status){
		td.appendChild(document.createTextNode("成功")); 
	}else{
		td.appendChild(document.createTextNode("失败")); 
	}
	tr.appendChild(td);
	var td = document.createElement("td");
	td.setAttribute("width", "275px");
	td.className = "log_msg";
	var span = document.createElement("span");
	span.innerHTML = msg;
	td.appendChild(span); 
	tr.appendChild(td);
	
	tbody.appendChild(tr);
	
	//滚动条保持在最下。
	var log_body = document.getElementById("log_body");
	log_body.scrollTop = log_body.scrollHeight; 
}

function runMission() {
    var tools = new happyfarm.util.Tools();
    var job = new happyfarm.util.Job();

    //生成登录人的信息
    var result = job.getUserInfo();
    if (result) {
        if (result.user) {
            var levelArray = tools.getLevel(result.exp);
            document.getElementById("myExp").innerHTML = result.exp;
            document.getElementById("myMoney").innerHTML = result.user.money;
            document.getElementById("myLevel").innerHTML = levelArray[0];
            document.getElementById("myLastExp").innerHTML = levelArray[1];
        }
    }

    //取得用户仓库信息
    getUserCrop();

    if (targetMission.length == 0) {
        return;
    }
	
	//设定维护间隔，60分钟
    var nextTime = 60 * 60;
    timeout = window.setTimeout(function() {
        Concurrent.Thread.create(startApp)
    },
    nextTime * 1000);

    //设定线程数目
    if (document.getElementById("threadNum").value != "" && !isNaN(document.getElementById("threadNum").value)) {
        threadNum = parseInt(document.getElementById("threadNum").value);
    } else {
        threadNum = 5;
    }

    //设定重试间隔
    if (document.getElementById("retryTime").value == "" && isNaN(document.getElementById("retryTime").value)) {
        retryTime = 100;
    }
    retryTime = parseInt(document.getElementById("retryTime").value);

    //设定重试次数
    if (document.getElementById("retry").value == "" && isNaN(document.getElementById("retry").value)) {
        document.getElementById("retry").value = 5;
    }
    retry = parseInt(document.getElementById("retry").value);

	//生成任务列表
    buildTask();

    //忽略本次维护完成成熟的农作物
    if (document.getElementById("ignoreCrops").checked) {
        while (true) {
            //忽略本次维护完成成熟的农作物，并延迟5秒判断
            if (targetMission[0].time - (tools.getLocalTime() - targetMission[0].localTime) - 3 < 0) {
                targetMission.splice(0, 1);
            } else {
                break;
            }
        }
    }

    //设定好友提前时间
    bTime = parseFloat(document.getElementById("beforeTime").value);
    //设定自己提前时间
    my_bTime = parseFloat(document.getElementById("myBeforeTime").value);
	
	//启动任务线程
	Concurrent.Thread.create(run, job, tools);
	
    //默认显示任务明细
    openDialog("task_area");

    document.title = "QQ农场辅助工具V1.0";
}

function buildTask(){
    var tools = new happyfarm.util.Tools();

    //排序任务列表
    targetMission.sort(function(a, b) {
        return (parseInt(a["time"]) + parseInt(a["serverTime"])) - (parseInt(b["time"]) + parseInt(b["serverTime"]));
    });
	
	//生成任务列表
    var taskArea = document.getElementById("task_detail");
    taskArea.innerHTML = "";
    //临时计数
    var n = 0;
    for (var i = 0; i < targetMission.length; i++) {
		
        if (i >= 15) {
            break;
        }

        //添加任务
        var task = document.createElement("div");
        task.className = "task_param";
        //任务序号
        var taskNo = document.createElement("div");
        taskNo.className = "task_param_no";
        taskNo.innerHTML = i + 1;
        task.appendChild(taskNo);
        //任务用户
        var taskUser = document.createElement("div");
        taskUser.className = "task_param_user";
        taskUser.innerHTML = targetMission[i].owner.userName;
        task.appendChild(taskUser);
        //任务名称
        var taskName = document.createElement("div");
        taskName.className = "task_param_name";
        taskName.innerHTML = targetMission[i].farm.cName;
        task.appendChild(taskName);
        //任务时间
        var taskTime = document.createElement("div");
        taskTime.className = "task_param_time";
        var time = tools.toUnixTime(parseInt(targetMission[i].serverTime) + parseInt(targetMission[i].time));
        taskTime.innerHTML = time.substr(11, 8);
        task.appendChild(taskTime);
        taskArea.appendChild(task);
    }
}

function run(job, tools){
	//启动任务线程
	while(targetMission.length > 0){
		Concurrent.Thread.create(missionTime, job, tools);
		Concurrent.Thread.sleep(200);
	}
}

//更新倒计时的时间
function missionTime(job, tools) {
    var mission = targetMission[0];
    var mine = 0;

    //设定提前摘取时间
    if (mission.owner.uId == myId) {
        bTime = my_bTime;
        mine = 1;
    }
    var misTime = parseInt(mission.time) - (tools.getLocalTime() - mission.localTime) - parseInt(bTime);

    document.getElementById("targetMisTime").innerHTML = tools.culTime(misTime).substr(0, 11) + " | " + targetMission.length + " 个任务";
    document.getElementById("targetMisName").innerHTML = mission.owner.userName + " | " + (parseInt(mission.farmIndex) + 1) + "号地 | " + mission.farm.cName;

    //时间到了，启动任务
    if (misTime < 0) {
		
        //删除当前任务
        targetMission.shift();
		
		//启动任务
		Concurrent.Thread.create(missionRun, job, mission, mine);		
        
		//生成任务列表
		buildTask();
    }
}

function missionRun(job, mission, mine){
	for(var i=0;i<parseInt(retry);i++){
		var result = job.getCrops(mission.owner.uId, mission.farmIndex, mine, null, mission.owner.uin);

        //失败
		if (result.code == 0 || result.harvest == 0) {
		
			//判断是否处于健康保护模式
			if (result.direction == "decode error") {
				addLog(mission.owner.userName, "第" + mission.farmIndex + "块地", mission.farm.cName, 0, false, "健康保护模式");
				break;
			}else if(result.direction.indexOf("狗") >= 0 || result.direction.indexOf("红土地") >= 0 || result.direction.indexOf("你不在") >= 0){
				addLog(mission.owner.userName, "第" + mission.farmIndex + "块地", mission.farm.cName, 0, false, result.direction);
				break;
			}else{
				addLog(mission.owner.userName, "第" + mission.farmIndex + "块地", mission.farm.cName, 0, false, result.direction);
			}
        } else {
            //成功
            if (mission.owner.uId == myId) {
                if (parseInt(result.harvest) > 0) {
                    //是否启用自动种菜功能和丰收后立即种菜
                    if (window.auto_crops_run && window.auto_farm_run) {
                        for (var c = 0; c < cropsInfo.length; c++) {
                            //从种子列表中找到当前的种子信息
                            if (mission.farm.a == cropsInfo[c].cId) {
                                //当前农作物所处的种植季判断，以便来区分是否可以锄地
                                if (mission.farm.j == parseInt(cropsInfo[c].maturingTime) - 1) {
                                    //锄地
                                    job.hoeing(mission.owner.uId, mission.farmIndex, mission.owner.indexId, mission.owner.uin);
                                    //耕种
                                    job.doFarming(mission.owner, mission.farmIndex, mission.owner.uin);
                                }
                                break;
                            }

                        }
                    }
                }
            }

            addLog(mission.owner.userName, "第" + mission.farmIndex + "块地", mission.farm.cName, result.harvest, true, "");
            break;
        }	
		
		//设定重试间隔
		Concurrent.Thread.sleep(retryTime);
	}
}

defClass(happyfarm.util, "AppLoader", null, function(AppLoader, AppLoader_prototype){
    AppLoader_prototype.init = function(){
		
    };
	
    //创建好友列表
    AppLoader_prototype.creatFriendList = function(i){
		
		//创建一个好友卡片
		this.createFriend(userArray[i], document.getElementById("friend_area"));
        
        if (friendRecords != null && friendRecords.length > 0) {
        
            //非首次生成
            for (var j = 0; j < friendRecords.length; j++) {
                if (userArray[i].uId == friendRecords[j].getAttribute("userId")) {
                    if (friendRecords[j].getAttribute("check") == "true") {
                        userArray[i]["check"] = true;
                    } else {
                        userArray[i]["check"] = false;
                    }
                    break;
                }
            }
        } else {
            //首次生成列表时默认全选
            userArray[i]["check"] = true;
        }
        document.getElementById(userArray[i].uId).checked = userArray[i]["check"];
    };
	
	AppLoader_prototype.createFriend = function(friend, area){
		
        var me = this;
		
		var tools = new happyfarm.util.Tools();
		
		//好友卡片
		var friendCard = document.createElement("div");
		friendCard.setAttribute("id", friend.uid);
		friendCard.setAttribute("class", "friend_card");
		friendCard.setAttribute("className", "friend_card");
		area.appendChild(friendCard);
		
		//好友级别区域
		var friendGrade = document.createElement("div");
		friendGrade.setAttribute("id", friend.uid + "_grade");
		friendGrade.setAttribute("class", "friend_grade");
		friendGrade.setAttribute("className", "friend_grade");
		friendGrade.innerHTML = tools.getLevel(friend.exp)[0];
		friendCard.appendChild(friendGrade);
		
		//好友详细信息区域
		var friendDetail = document.createElement("div");
		friendDetail.setAttribute("id", friend.uid + "_detail");
		friendDetail.setAttribute("class", "friend_detail");
		friendDetail.setAttribute("className", "friend_detail");
		friendCard.appendChild(friendDetail);
		
		//好友数据头部1
		var friendParamHead1 = document.createElement("div");
		friendParamHead1.setAttribute("class", "friend_param");
		friendParamHead1.setAttribute("className", "friend_param");
		friendParamHead1.innerHTML = "经验";
		friendDetail.appendChild(friendParamHead1);
		
		//好友数据头部2
		var friendParamHead2 = document.createElement("div");
		friendParamHead2.setAttribute("class", "friend_param");
		friendParamHead2.setAttribute("className", "friend_param");
		friendParamHead2.innerHTML = "金币";
		friendDetail.appendChild(friendParamHead2);
		
		//好友数据头部3
		var friendParamHead3 = document.createElement("div");
		friendParamHead3.setAttribute("class", "friend_param");
		friendParamHead3.setAttribute("className", "friend_param");
		friendParamHead3.innerHTML = "狗";
		friendDetail.appendChild(friendParamHead3);
		
		//好友数据头部4
		var friendParamHead4 = document.createElement("div");
		friendParamHead4.setAttribute("class", "friend_param");
		friendParamHead4.setAttribute("className", "friend_param");
		friendParamHead4.innerHTML = "选择";
		friendDetail.appendChild(friendParamHead4);
		
		//好友数据内容1
		var friendParamContent1 = document.createElement("div");
		friendParamContent1.setAttribute("id", friend.uid + "_param1");
		friendParamContent1.setAttribute("class", "friend_param_content");
		friendParamContent1.setAttribute("className", "friend_param_content");
		friendParamContent1.innerHTML = friend.exp;
		friendDetail.appendChild(friendParamContent1);
		
		//好友数据内容2
		var friendParamContent2 = document.createElement("div");
		friendParamContent2.setAttribute("id", friend.uid + "_param2");
		friendParamContent2.setAttribute("class", "friend_param_content");
		friendParamContent2.setAttribute("className", "friend_param_content");
		friendParamContent2.innerHTML = friend.money;
		friendDetail.appendChild(friendParamContent2);
		
		//好友数据内容3
		var friendParamContent3 = document.createElement("div");
		friendParamContent3.setAttribute("id", friend.uid + "_param3");
		friendParamContent3.setAttribute("class", "friend_param_content");
		friendParamContent3.setAttribute("className", "friend_param_content");
		friendDetail.appendChild(friendParamContent3);
		
		//好友数据内容4
		var friendParamContent4 = document.createElement("div");
		friendParamContent4.setAttribute("id", friend.uid + "_param4");
		friendParamContent4.setAttribute("class", "friend_param_content");
		friendParamContent4.setAttribute("className", "friend_param_content");
		var flistBtn = document.createElement("input");
        flistBtn.setAttribute("id", friend.uId);
        flistBtn.setAttribute("type", "checkbox");
        flistBtn.checked = true;
        flistBtn.onclick = function(){
            me.friendChoose(this);
        };
        friendParamContent4.appendChild(flistBtn);
		friendDetail.appendChild(friendParamContent4);
		
		//好友数据底部1
		var friendParamBottom1 = document.createElement("div");
		friendParamBottom1.className = "friend_param";
		friendDetail.appendChild(friendParamBottom1);
		
		//好友数据底部2
		var friendParamBottom2 = document.createElement("div");
		friendParamBottom2.className = "friend_param";
		friendDetail.appendChild(friendParamBottom2);
		
		//好友数据底部3
		var friendParamBottom3 = document.createElement("div");
		friendParamBottom3.className = "friend_param";
		friendDetail.appendChild(friendParamBottom3);
		
		//好友数据底部4
		var friendParamBottom4 = document.createElement("div");
		friendParamBottom4.className = "friend_param";
		friendDetail.appendChild(friendParamBottom4);
		
		//好友头像
		var friendHeadPic = document.createElement("div");
		friendHeadPic.setAttribute("id", friend.uid + "_headPic");
		friendHeadPic.setAttribute("class", "friend_headPic");
		friendHeadPic.setAttribute("className", "friend_headPic");
		var headPic = document.createElement("img");
		headPic.setAttribute("class", "friend_headPic_img");
		headPic.setAttribute("className", "friend_headPic_img");
		if(friend.headPic != null && friend.headPic.length > 1){
			headPic.setAttribute("src", friend.headPic);
		}else{
			headPic.setAttribute("src", "http://qlogo.store.qq.com/qzone/" + friend.uin + "/" + friend.uin + "/100");
		}
		headPic.setAttribute("border", "0");
		headPic.setAttribute("title", friend.userName);
		headPic.setAttribute("alt", friend.userName);
		friendHeadPic.appendChild(headPic);
		friendCard.appendChild(friendHeadPic);
	};
    
    AppLoader_prototype.creatCropsList = function(i){
        var me = this;
        //生成默认播种种子列表
        document.getElementById("defult-crop").options[document.getElementById("defult-crop").options.length] = new Option(cropsInfo[i].cName, cropsInfo[i].cId);
        //生成默认播种红种子列表
		if(cropsInfo[i].cId > 200 || cropsInfo[i].cId == "126"){
			document.getElementById("defult-red-crop").options[document.getElementById("defult-red-crop").options.length] = new Option(cropsInfo[i].cName, cropsInfo[i].cId);
		}
		//生成有狗粮不偷种子列表1
        document.getElementById("dogCrops1").options[document.getElementById("dogCrops1").options.length] = new Option(cropsInfo[i].cName, cropsInfo[i].cId);
		//生成有狗粮不偷种子列表2
        document.getElementById("dogCrops2").options[document.getElementById("dogCrops2").options.length] = new Option(cropsInfo[i].cName, cropsInfo[i].cId);
		//生成有狗粮不偷种子列表3
		document.getElementById("dogCrops3").options[document.getElementById("dogCrops3").options.length] = new Option(cropsInfo[i].cName, cropsInfo[i].cId);
        
        //生成农作物种子列表
        var cropsRow = document.createElement("tr");
        cropsRow.setAttribute("id", "cropsRow" + i);
        cropsRow.setAttribute("align", "center");
        //隔行换色
        if (i % 2 != 0) {
            cropsRow.setAttribute("class", "row-bgcolor");
            cropsRow.setAttribute("className", "row-bgcolor");
        }
        var cropsCell = document.createElement("td");
		var ropsButton = document.createElement("input");
        ropsButton.setAttribute("id", "c_"+cropsInfo[i].cId);
        ropsButton.setAttribute("type", "checkbox");
        //ropsButton.setAttribute("checked", "false"); 低版本IE不支持
        ropsButton.onclick = function(){
            me.cropsChoose(this);
        };
        cropsCell.appendChild(ropsButton);
        cropsRow.appendChild(cropsCell);
		cropsCell = document.createElement("td");
        cropsCell.appendChild(document.createTextNode(cropsInfo[i].cId));
        cropsRow.appendChild(cropsCell);
        cropsCell = document.createElement("td");
        cropsCell.appendChild(document.createTextNode(cropsInfo[i].cName));
        cropsRow.appendChild(cropsCell);
        cropsCell = document.createElement("td");
        cropsCell.appendChild(document.createTextNode(parseInt(cropsInfo[i].growthCycle) / 3600));
        cropsRow.appendChild(cropsCell);
        cropsCell = document.createElement("td");
        cropsCell.appendChild(document.createTextNode(cropsInfo[i].maturingTime));
        cropsRow.appendChild(cropsCell);
        cropsCell = document.createElement("td");
        cropsCell.appendChild(document.createTextNode(cropsInfo[i].expect));
        cropsRow.appendChild(cropsCell);
        cropsCell = document.createElement("td");
        cropsCell.appendChild(document.createTextNode(cropsInfo[i].output));
        cropsRow.appendChild(cropsCell);
        cropsCell = document.createElement("td");
        cropsCell.appendChild(document.createTextNode(cropsInfo[i].sale));
        cropsRow.appendChild(cropsCell);
        cropsCell = document.createElement("td");
        cropsCell.appendChild(document.createTextNode(cropsInfo[i].price));
        cropsRow.appendChild(cropsCell);
        cropsCell = document.createElement("td");
        cropsCell.appendChild(document.createTextNode(cropsInfo[i].cLevel));
        cropsRow.appendChild(cropsCell);
        cropsCell = document.createElement("td");
        cropsCell.appendChild(document.createTextNode(cropsInfo[i].cropExp));
        cropsRow.appendChild(cropsCell);
        
        //生成商店信息
        document.getElementById("crops").appendChild(cropsRow);
		
		//生成备选种子列表
        var cId = cropsInfo[i].cId;
		var cName = cropsInfo[i].cName;
		var shop = document.getElementById("shop");
		var seed = document.createElement("div");
		seed.id = cId;
		if(cId>200 || cId=="126"){
			seed.className = "seedRed";
		}else{
			seed.className = "seed";
		}
		seed.onclick = function(){
			if(selectFarm == null){
				alert("请选择一块农田！");
			}else{
				var farm = document.getElementById("farmContent" + selectFarm);
				var farmTitle = document.getElementById("farmContent" + selectFarm);
				//红土地必须中红土地种子
				if(farmTitle.innerHTML.indexOf("红") < 0 && (cId>200 || cId=="126")){
					alert("红土地种子只能播种在红土地！");
				}
				//判断子节点个数，超过3个不予追加种子。
				if(farm.childNodes.length != 3){
					var seedCopy = seed.cloneNode(true);
					seedCopy.style.width="100%";
					seedCopy.onclick = function(){
						seedCopy.parentNode.removeChild(seedCopy);
					}
					farm.appendChild(seedCopy);
				}
			}
		}
		var seedName = document.createTextNode(cName);
		seed.appendChild(seedName);
		shop.appendChild(seed);
		
		if (cropsRecords != null && cropsRecords.length > 0) {
        
            //非首次生成
            for (var j = 0; j < cropsRecords.length; j++) {
                if (cropsInfo[i].cId == cropsRecords[j].getAttribute("cId")) {
                    if (cropsRecords[j].getAttribute("check") == "true") {
                        cropsInfo[i]["check"] = true;
                    } else {
                        cropsInfo[i]["check"] = false;
                    }
                    break;
                }
            }
        } else {
            //首次生成列表时默认全选
            cropsInfo[i]["check"] = true;
        }
        document.getElementById("c_"+cropsInfo[i].cId).checked = cropsInfo[i]["check"];
    };
    
    
    
    //更新进度条
    AppLoader_prototype.updateProgressBars = function(num, count){
        var progBar = document.getElementById("progMain");
        progBar.style.width = num / count * 100 + "%";
        progBar.innerHTML = Math.round(num / count * 100) + "%";
    };
    
	//在商店列表中加入或去除一个种子
    AppLoader_prototype.cropsChoose = function(choose){
        for (var i = 0; i < cropsInfo.length; i++) {
            if (cropsInfo[i].cId == choose.id.substr(2, choose.id.length)) {
                cropsInfo[i]["check"] = choose.checked;
				break;
            }
        }
    };
	
    //在维护列表中加入或去除一个好友
    AppLoader_prototype.friendChoose = function(choose){
        for (var i = 0; i < userArray.length; i++) {
            if (userArray[i].uId == choose.id) {
                userArray[i]["check"] = choose.checked;
            }
        }
    };
    
    //在维护列表中选择全部好友
    AppLoader_prototype.friendChooseAll = function(){
        for (var i = 0; i < userArray.length; i++) {
            userArray[i]["check"] = true;
            document.getElementById(userArray[i].uId).checked = userArray[i]["check"];
        }
    };
    
    //在维护列表中反选全部好友
    AppLoader_prototype.friendChooseInversion = function(){
        for (var i = 0; i < userArray.length; i++) {
            if (userArray[i]["check"]) {
                userArray[i]["check"] = false;
            } else {
                userArray[i]["check"] = true;
            }
            document.getElementById(userArray[i].uId).checked = userArray[i]["check"];
        }
    };
    
    //在维护列表中自定义选择好友数
    AppLoader_prototype.friendChooseCustom = function(){
        var from = document.getElementById("friendChooseFrom").value;
        var to = document.getElementById("friendChooseTo").value;
        
        if (from == "") {
            from = 0;
        } else {
            if (isNaN(from)) {
                alert("开始序号请输入数字");
                return;
            } else if (from <= 0) {
                alert("开始序号应大于0");
                return;
            }
            from = from - 1;
        }
        
        if (to == "") {
            to = userArray.length;
        } else {
            if (isNaN(to)) {
                alert("结束序号请输入数字");
                return;
            } else if (to <= 0) {
                alert("结束序号应大于0");
                return;
            }
            to = to - 1;
        }
        
        if (from >= to) {
            alert("结束序号应大于开始序号！");
            return;
        }
        
        for (var i = 0; i < userArray.length; i++) {
            if (i >= from && i <= to) {
                userArray[i]["check"] = true;
            } else {
                userArray[i]["check"] = false;
            }
            document.getElementById(userArray[i].uId).checked = userArray[i]["check"];
        }
    };
    
    //增加一个种子
    AppLoader_prototype.addReadyCrops = function(cId, cName, type){
        var tmpCrops = new Array();
        tmpCrops.push(cId, cName, type);
        readyCrops.push(tmpCrops);
    };
    
    //升级版本检测
    AppLoader_prototype.checkUpgrade = function(){
        var tools = new happyfarm.util.Tools();
        tools.checkUpgrade();
    };
    
    //取得好友配置记录
    AppLoader_prototype.getfriendConfig = function(){
        var tools = new happyfarm.util.Tools();
        
        var fct = function(xmlDoc){
            var appLoader = new happyfarm.util.AppLoader();
            
            friendRecords = xmlDoc.getElementsByTagName("record");
            
            //在我的好友里生成列表
            for (var i = 0; i < userArray.length; i++) {
                appLoader.creatFriendList(i);
            }
        };
        tools.getConfig(myId + "\\friend.config", fct);
    };
	
	//取得选择偷菜配置记录
    AppLoader_prototype.getCropsConfig = function(){
        var tools = new happyfarm.util.Tools();
        
        var fct = function(xmlDoc){
            var appLoader = new happyfarm.util.AppLoader();
            
            cropsRecords = xmlDoc.getElementsByTagName("record");
            
            //生成种子选择列表
            for (var i = 0; i < cropsInfo.length; i++) {
				appLoader.creatCropsList(i);
			}
        };
        tools.getConfig(myId + "\\crops.config", fct);
    };
	
	//取得农田播种配置记录
    AppLoader_prototype.getFarmConfig = function(farms){
        var tools = new happyfarm.util.Tools();
        
        var fct = function(xmlDoc){
            var job = new happyfarm.util.Job();
            
            farmRecords = xmlDoc.getElementsByTagName("record");
			
            var myFarm = document.getElementById("farmland");
            //生成农田播种列表
            for (var i = 0; i < farms.length; i++) {
				job.createUserFarm(i, farms[i], myFarm);
			}
        };
        tools.getConfig(myId + "\\farm.config", fct);
    };
    
    //取得系统配置信息
    AppLoader_prototype.getSysConfig = function(){
        var tools = new happyfarm.util.Tools();
        
        var fct = function(xmlDoc){
            if (xmlDoc.getElementsByTagName("system").length > 0) {
                var param = new Array("weeds", "borers", "dryland", "crope", "dog", "dogCrops1", "dogCrops2", "dogCrops3", "s-theft", "u-theft", "beforeTime", "myBeforeTime", "Anti-theft", "Auto-feed", "defult-crop", "defult-red-crop", "defult-crop-first", "Auto-fertilizer", "Auto-crops", "Auto-saleAll", "Auto-act", "Auto-farm", "retry", "ignoreCrops", "threadNum", "retryTime", "brushExpInterval", "harvestDetail", "farmDetail", "brushQQInterval", "alertSound", "alertSysSound", "intervalTimeCheck", "intervalTimeValue");
                for (var i = 0; i < param.length; i++) {
                    if (xmlDoc.getElementsByTagName(param[i])[0].getAttribute("value") == "true") {
                        document.getElementById(param[i]).checked = true;
                    } else if (xmlDoc.getElementsByTagName(param[i])[0].getAttribute("value") == "false") {
                        document.getElementById(param[i]).checked = false;
                    } else {
                        document.getElementById(param[i]).value = xmlDoc.getElementsByTagName(param[i])[0].getAttribute("value");
                    }
                }
            }
        };
        tools.getConfig(myId + "\\system.config", fct);
    };
    
    //保存好友配置
    AppLoader_prototype.saveFriendConfig = function(){
        var tools = new happyfarm.util.Tools();
        
        var content = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "\n";
        content += "<friend>" + "\n";
        for (var i = 0; i < userArray.length; i++) {
            content += "<record userId=\"" + userArray[i].uId + "\" check=\"" + userArray[i].check + "\"/>" + "\n";
        }
        content += "</friend>";
        tools.saveConfig(content, "friend", null, true);
    };
	
	//保存种子配置
    AppLoader_prototype.saveCropsConfig = function(){
        var tools = new happyfarm.util.Tools();
        
        var content = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "\n";
        content += "<crops>" + "\n";
        for (var i = 0; i < cropsInfo.length; i++) {
            content += "<record cId=\"" + cropsInfo[i].cId + "\" check=\"" + cropsInfo[i].check + "\"/>" + "\n";
        }
        content += "</crops>";
        tools.saveConfig(content, "crops", null, false);
    };
	
	//保存农田播种配置
    AppLoader_prototype.saveFarmConfig = function(){
        var tools = new happyfarm.util.Tools();
        
        var content = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "\n";
        content += "<farm>" + "\n";
        for (var i = 0; i < 18; i++) {
			var farm = document.getElementById("farmContent"+i);
			if(farm){
				for(var j = 0;j<farm.childNodes.length;j++){
					content += "<record fId=\"" + i + "\" cId=\"" + farm.childNodes[j].id + "\" cName=\"" + farm.childNodes[j].innerHTML + "\"/>" + "\n";
				}
			}
        }
        content += "</farm>";
        tools.saveConfig(content, "farm", null, false);
    };
    
    //保存系统配置
    AppLoader_prototype.saveSysConfig = function(){
        var tools = new happyfarm.util.Tools();
        
        var content = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "\n";
        content += "<system>" + "\n";
        content += "<weeds value=\"" + document.getElementById("weeds").checked + "\"/>" + "\n";
        content += "<borers value=\"" + document.getElementById("borers").checked + "\"/>" + "\n";
        content += "<dryland value=\"" + document.getElementById("dryland").checked + "\"/>" + "\n";
        content += "<crope value=\"" + document.getElementById("crope").checked + "\"/>" + "\n";
        content += "<dog value=\"" + document.getElementById("dog").checked + "\"/>" + "\n";
		content += "<dogCrops1 value=\"" + document.getElementById("dogCrops1").value + "\"/>" + "\n";
		content += "<dogCrops2 value=\"" + document.getElementById("dogCrops2").value + "\"/>" + "\n";
		content += "<dogCrops3 value=\"" + document.getElementById("dogCrops3").value + "\"/>" + "\n";
        content += "<s-theft value=\"" + document.getElementById("s-theft").checked + "\"/>" + "\n";
        content += "<u-theft value=\"" + document.getElementById("u-theft").checked + "\"/>" + "\n";
        content += "<beforeTime value=\"" + document.getElementById("beforeTime").value + "\"/>" + "\n";
        content += "<myBeforeTime value=\"" + document.getElementById("myBeforeTime").value + "\"/>" + "\n";
        content += "<Anti-theft value=\"" + document.getElementById("Anti-theft").checked + "\"/>" + "\n";
        content += "<Auto-feed value=\"" + document.getElementById("Auto-feed").checked + "\"/>" + "\n";
        content += "<defult-crop value=\"" + document.getElementById("defult-crop").value + "\"/>" + "\n";
        content += "<defult-red-crop value=\"" + document.getElementById("defult-red-crop").value + "\"/>" + "\n";
		content += "<defult-crop-first value=\"" + document.getElementById("defult-crop-first").checked + "\"/>" + "\n";
        content += "<Auto-fertilizer value=\"" + document.getElementById("Auto-fertilizer").checked + "\"/>" + "\n";
        content += "<Auto-crops value=\"" + document.getElementById("Auto-crops").checked + "\"/>" + "\n";
        content += "<Auto-saleAll value=\"" + document.getElementById("Auto-saleAll").checked + "\"/>" + "\n";
        content += "<Auto-act value=\"" + document.getElementById("Auto-act").checked + "\"/>" + "\n";
		content += "<Auto-farm value=\"" + document.getElementById("Auto-farm").checked + "\"/>" + "\n";
        content += "<retry value=\"" + document.getElementById("retry").value + "\"/>" + "\n";
		content += "<ignoreCrops value=\"" + document.getElementById("ignoreCrops").checked + "\"/>" + "\n";
		content += "<threadNum value=\"" + document.getElementById("threadNum").value + "\"/>" + "\n";
		content += "<retryTime value=\"" + document.getElementById("retryTime").value + "\"/>" + "\n";
		content += "<brushExpInterval value=\"" + document.getElementById("brushExpInterval").value + "\"/>" + "\n";
		content += "<harvestDetail value=\"" + document.getElementById("harvestDetail").checked + "\"/>" + "\n";
		content += "<farmDetail value=\"" + document.getElementById("farmDetail").checked + "\"/>" + "\n";
		content += "<brushQQInterval value=\"" + document.getElementById("brushQQInterval").value + "\"/>" + "\n";
		content += "<alertSound value=\"" + document.getElementById("alertSound").checked + "\"/>" + "\n";
		content += "<alertSysSound value=\"" + document.getElementById("alertSysSound").value + "\"/>" + "\n";
		content += "<intervalTimeCheck value=\"" + document.getElementById("intervalTimeCheck").checked + "\"/>" + "\n";
		content += "<intervalTimeValue value=\"" + document.getElementById("intervalTimeValue").value + "\"/>" + "\n";
        content += "</system>";
        tools.saveConfig(content, "system", null, true);
		//保存种子配置
		this.saveCropsConfig();
		//保存农田播种信息
		this.saveFarmConfig();
    };
});

var appLoader = new happyfarm.util.AppLoader();
